package com.ljkj.blockpay.ui.activity;

import static android.content.ContentValues.TAG;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.kongzue.baseokhttp.util.JsonMap;
import com.ljkj.blockpay.R;
import com.ljkj.blockpay.basedata.BaseActivity;
import com.ljkj.blockpay.databinding.ActivityExchangeBinding;
import com.ljkj.blockpay.model.RechargeModel;
import com.ljkj.blockpay.presenter.ExchangePresenter;
import com.ljkj.blockpay.presenter.inter.ExchangeInter;
import com.ljkj.blockpay.util.ToggleToActivity;
import com.ljkj.blockpay.widget.ClickListener;
import com.ljkj.blockpay.widget.CommonDialog;
import com.ljkj.blockpay.widget.XCDropDownListView;
import com.luck.picture.lib.tools.ToastUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.PrimitiveIterator;

//兑换界面
public class ExchangeActivity extends BaseActivity<ActivityExchangeBinding, ExchangePresenter> implements ExchangeInter.ExchangeInterView, ClickListener {


    private static final int EDIT_OK = 800;
    private CommonDialog offerExpiredDialog;
    private CommonDialog confirmchangeDialog;
    private String balance;
    private String currencyType;
    private int accuracy;
    private String exchangeRate;
    private String targetServiceAmount;
    private String preOrderId;
    private Long preOrderOvertime;
    private String targetActualAmount;
    private String targetCurrency;
    private String exchangeRateDesc;
    private String currencyName;
    private String currencyImg;
    private String targetAmount;
    private String origin;
    private BigDecimal originNumber;
    private String getCurrencyImg;
    private String getCurrencyName;
    private int intValue;
    private long time;
    private boolean upAndDown = false;
    private CommonDialog mDealDialog;
    private String orderId;
    private ImageView upicon;
    private TextView upnumber;
    private TextView upunit;
    private ImageView downicon;
    private TextView downnumber;
    private TextView downunit;
    private TextView parities;
    private TextView servicecharge;
    private TextView getmoney;
    private String originCurrency;


    @Override
    public int initContentView() {
        return R.layout.activity_exchange;
    }

    @Override
    protected ExchangePresenter createPresenter() {
        return new ExchangePresenter(this, this);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setOnClick(this::onClick);
        binding.tvTitle.setTitleContent(R.string.homeexchange);
        binding.tvTitle.setLeftBackFinish(this);
    }

    @Override
    protected void initData() {
        super.initData();
        getPresenter().getNetAccuracy();
        binding.etNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().isEmpty()) {
                    //空
                    if (countDownTimer != null) {
                        cancleTime();
                    }
                    binding.tvGetmoney.setText("");

                } else {
                    getEditText();
                }
            }
        });
    }

    private CountDownTimer countDownTimer;
    private CommonDialog builder;

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.tv_all:
                break;

            case R.id.tv_unit:
                ToggleToActivity.toSelectCurrencyActivity(this, 10);
                break;
            case R.id.iv_exchange:
                jiaohuan();
                break;
            case R.id.tv_unitbtc:
                ToggleToActivity.toSelectCurrencyActivity(this, 11);
                break;
            case R.id.btn_next:
                if (currencyName.equals(getCurrencyName)){
                    Toast.makeText(baseContext, "不能选择同一个币种！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (preOrderOvertime != 0){
                    showDialogDuihuan();
                }else{
                    timeEnd();
                }
                break;
        }
    }

    public void showDialogDuihuan() {
        confirmchangeDialog = CommonDialog.Builder.with(ExchangeActivity.this).setContentView(R.layout.fragment_confirm_change)
                .setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        confirmchangeDialog.dismiss();
                    }
                })
                .setCancelable(true).setOnClickListener(R.id.btn_ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        builder = CommonDialog.Builder.with(ExchangeActivity.this).setContentView(R.layout.codeedit_layout)
                                .setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        cancleTime();
                                        builder.dismiss();
                                    }
                                })
                                .setOnClickListener(R.id.btn_ok, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        getPresenter().createOrder(5, preOrderId, "123456");
                                        builder.dismiss();
                                    }
                                }).fullWidth().setOnKeyListener((dialogInterface, i, keyEvent) -> false)
                                .setCancelable(true).create();
                        builder.show();
                    }
                }).fullWidth().forGravity(Gravity.BOTTOM).setOnKeyListener((dialogInterface, i, keyEvent) -> false).create();
        Button btn = confirmchangeDialog.getView(R.id.btn_ok);

        cancleTime();
        countDownTimer = new CountDownTimer(preOrderOvertime, 1000) {
            @Override
            public void onTick(long l) {
                preOrderOvertime = l;
                btn.setText(getResources().getString(R.string.btn_next) + "(" + preOrderOvertime / 1000 + ")");
            }

            @Override
            public void onFinish() {
                timeEnd();
            }
        };
        countDownTimer.start();

        upicon = confirmchangeDialog.findViewById(R.id.iv_icon);
        upnumber = confirmchangeDialog.findViewById(R.id.tv_nums);
        upunit = confirmchangeDialog.findViewById(R.id.tv_unit);
        downicon = confirmchangeDialog.findViewById(R.id.iv_get);
        downnumber = confirmchangeDialog.findViewById(R.id.tv_getnum);
        downunit = confirmchangeDialog.findViewById(R.id.tv_getunit);
        parities = confirmchangeDialog.findViewById(R.id.tv_parities);
        servicecharge = confirmchangeDialog.findViewById(R.id.tv_servicecharge);
        getmoney = confirmchangeDialog.findViewById(R.id.tv_getmoney);
        //确认兑换Dialog 上下数值及图片
        upnumber.setText(origin);
        downnumber.setText(targetAmount);
        upunit.setText(currencyName);
        downunit.setText(getCurrencyName);
        Glide.with(this).load(currencyImg).into(upicon);
        Glide.with(this).load(getCurrencyImg).into(downicon);
        parities.setText(getResources().getString(R.string.paritie) + exchangeRateDesc);
        servicecharge.setText(getResources().getString(R.string.servicecharg) + targetServiceAmount);
        getmoney.setText(getResources().getString(R.string.inlinefor) + targetActualAmount);
        confirmchangeDialog.show();
    }

    private void cancleTime() {
        if (countDownTimer != null){
            countDownTimer.cancel();
            countDownTimer = null;
            binding.btnNext.setText("下一步");
        }
    }


    private void jiaohuan() {
        Animation animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setFillAfter(true);
        animation.setDuration(1000);
        animation.setInterpolator(new AccelerateInterpolator());
        binding.etNum.setText("");
        binding.ivExchange.startAnimation(animation);

        String value = currencyName;
        currencyName = getCurrencyName;
        getCurrencyName = value;

        String imageValue = currencyImg;
        currencyImg = getCurrencyImg;
        getCurrencyImg = imageValue;

        updateUi();
    }

    private void updateUi() {
        //up
        binding.tvUnit.setText(currencyName);
        //up image
        Glide.with(baseContext).load(currencyImg).into(binding.ivIcon);
        //down
        binding.tvUnitbtc.setText(getCurrencyName);
        //down image
        Glide.with(ExchangeActivity.this).load(getCurrencyImg).into(binding.ivGeticon);
        getPresenter().SearchCurrencyBalance(currencyName, 5);
        getPresenter().preConfirm(0, 5, currencyName, getCurrencyName);
    }

    /**
     * Description: 小数位数限定
     */

    public class DecimalInputTextWatcher implements TextWatcher {

        private static final String Period = ".";
        private static final String Zero = "0";

        /**
         * 需要设置该 DecimalInputTextWatcher 的 EditText
         */
        private EditText editText = null;

        /**
         * 默认  小数的位数   2 位
         */
        private static final int DEFAULT_DECIMAL_DIGITS = 2;

        private int decimalDigits;// 小数的位数
        private int totalDigits;//最大长度

        /**
         * @param editText      editText
         * @param totalDigits   最大长度
         * @param decimalDigits 小数的位数
         */
        public DecimalInputTextWatcher(EditText editText, int totalDigits, int decimalDigits) {
            if (editText == null) {
                throw new RuntimeException("editText can not be null");
            }
            this.editText = editText;
            if (totalDigits <= 0)
                throw new RuntimeException("totalDigits must > 0");
            if (decimalDigits <= 0)
                throw new RuntimeException("decimalDigits must > 0");
            this.totalDigits = totalDigits;
            this.decimalDigits = decimalDigits;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            try {
                String s = editable.toString();
                editText.removeTextChangedListener(this);
                //限制最大长度
                editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(totalDigits)});

                if (s.contains(Period)) {
                    //超过小数位限定位数,只保留限定小数位数
                    if (s.length() - 1 - s.indexOf(Period) > decimalDigits) {
                        s = s.substring(0,
                                s.indexOf(Period) + decimalDigits + 1);
                        editable.replace(0, editable.length(), s.trim());
                    }
                }
                //如果首位输入"."自动补0
                if (s.trim().equals(Period)) {
                    s = Zero + s;
                    editable.replace(0, editable.length(), s.trim());
                }
                //首位输入0时,不再继续输入
                if (s.startsWith(Zero)
                        && s.trim().length() > 1) {
                    if (!s.substring(1, 2).equals(Period)) {
                        editable.replace(0, editable.length(), Zero);
                    }
                }
                editText.addTextChangedListener(this);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void showNetAccuracy(List<RechargeModel> modelList) {
        //首次进入默认
        currencyType = modelList.get(0).getCurrencyType();
        accuracy = modelList.get(0).getNetwork().get(0).getCurrencyAccuracy();
        currencyName = modelList.get(0).getCurrencyName();
        currencyImg = modelList.get(0).getCurrencyImg();
        getCurrencyImg = modelList.get(1).getCurrencyImg();
        getCurrencyName = modelList.get(1).getCurrencyName();

        getPresenter().SearchCurrencyBalance(currencyType, 5);
        binding.etNum.addTextChangedListener(new DecimalInputTextWatcher(binding.etNum, accuracy, accuracy));
        binding.tvUnit.setText(modelList.get(0).getCurrencyName());

        Glide.with(ExchangeActivity.this).load(this.currencyImg).error(R.mipmap.app_icon).into(binding.ivIcon);
        Glide.with(ExchangeActivity.this).load(this.getCurrencyImg).error(R.mipmap.icon_error).into(binding.ivGeticon);
        binding.tvUnitbtc.setText(getCurrencyName);

        for (int i = 0; i < modelList.size(); i++) {
            Log.d("yuyuyu", modelList.get(i).getCurrencyName());

        }

    }

    @Override
    public void SearchCurrencySuccess(JsonMap jsonMap) {
        balance = jsonMap.getString("balance");
        binding.tvUsable.setText(balance);

    }

    @Override
    public void preConfirmSuccess(JsonMap jsonMapData) {
        exchangeRate = jsonMapData.getString("exchangeRate");
        targetServiceAmount = jsonMapData.getString("targetServiceAmount");
        preOrderId = jsonMapData.getString("preOrderId");
        if (!jsonMapData.getString("preOrderOvertime").equals("")){
            preOrderOvertime = Long.parseLong(jsonMapData.getString("preOrderOvertime"))*1000;
        }
        targetAmount = jsonMapData.getString("targetAmount");
        targetActualAmount = jsonMapData.getString("targetActualAmount");
        targetCurrency = jsonMapData.getString("targetCurrency");
        originCurrency = jsonMapData.getString("originCurrency");

        exchangeRateDesc = jsonMapData.getString("exchangeRateDesc");

        //汇率
        binding.tvParitiesnum.setText(exchangeRateDesc);
        //手续费
        binding.chargenum.setText(targetServiceAmount);
        //预计金额
        binding.tvGetmoney.setText(targetAmount);
        //实际到账金额
        binding.tvActual.setText(targetActualAmount);
       if (preOrderOvertime != null){
           binding.btnNext.setSelected(true);
           cancleTime();
           if (countDownTimer == null) {
               countDownTimer = new CountDownTimer(preOrderOvertime, 1000) {
                   @Override
                   public void onTick(long l) {
                       preOrderOvertime = l;
                       binding.btnNext.setText(getResources().getString(R.string.btn_next) + "(" + (l / 1000) + ")" + "s");
                   }

                   @Override
                   public void onFinish() {
                       timeEnd();
                   }
               };
               countDownTimer.start();
           }
       }


        //获得币种
//        binding.tvUnitbtc.setText(targetCurrency);
    }

    @Override
    public void getOrderDetails(JsonMap jsonMap) {

    }


    @Override
    public void getOrderDetails2(JsonMap jsonMap) {
        String orderIds = jsonMap.getString("orderId");
        ToggleToActivity.toTradingParticularActivity(ExchangeActivity.this, 5, orderIds);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancleTime();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 100) {
            return;
        }
        if (data.getExtras() != null) {
            Bundle bundle = data.getExtras();
            JsonMap jsonMap = JsonMap.parse(bundle.getString("jsonMap"));
            switch (requestCode) {
                case 10:
//                    if (jsonMap.getString("currencyName").equals(getCurrencyName)) {
//                        ToastUtils.s(ExchangeActivity.this, "不能选择一样的币");
//                        return;
//                    }
                    currencyName = jsonMap.getString("currencyName");
                    currencyImg = jsonMap.getString("currencyImg");
                    updateUi();
                    break;
                case 11:
//                    if (jsonMap.getString("currencyName").equals(currencyName)) {
//                        ToastUtils.s(ExchangeActivity.this, "不能选择一样的币");
//                        return;
//                    }
                    getCurrencyName = jsonMap.getString("currencyName");
                    getCurrencyImg = jsonMap.getString("currencyImg");
                    updateUi();
                    break;
                default:
            }

        }
    }


    //监听输入框
    public void getEditText() {
        origin = binding.etNum.getText().toString();
        if (!origin.isEmpty()) {
            originNumber = new BigDecimal(origin);
            getPresenter().preConfirm(originNumber, 5, currencyName, getCurrencyName);
        } else {
            getPresenter().preConfirm(0, 5, currencyName, getCurrencyName);
        }
    }
    public void timeEnd(){
        binding.btnNext.setText("下一步");
        if (offerExpiredDialog == null){
            offerExpiredDialog = CommonDialog.Builder.with(ExchangeActivity.this).setContentView(R.layout.offerexpired_layout)
                    .setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            offerExpiredDialog.dismiss();
                        }
                    }).setOnClickListener(R.id.btn_ok, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            offerExpiredDialog.dismiss();
                        }
                    }).setCancelable(true)
                    .formBottom(true)
                    .forGravity(Gravity.BOTTOM).setAnimations(R.anim.dialog_from_bottom_anim_out).fullWidth().setOnKeyListener((dialogInterface, i, keyEvent) -> false).create();
        }
        if (!offerExpiredDialog.isShowing()){
            offerExpiredDialog.show();
        }

    }

}